import element.base.Synt;
import element.base.Word;
import element.synt.CompUnit;
import intermediate_representation.InterRP;
import table.InterCodeTable;
import table.Table;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class Compiler {
    public static void main(String[] args) throws IOException {
        File infile = new File("testfile.txt");
        File outfile = new File("output.txt");
        File errorfile = new File("error.txt");
        File mipsfile = new File("mips.txt");

        //文件读取
        FileDeal fileDeal = new FileDeal(infile);
        try {
            fileDeal.readFile();
        } catch (IOException e) {
            System.out.println("IO error");
        }
        String procedure = fileDeal.getUnionlines();

//        FileWriter writer = new FileWriter(outfile);
//        writer.write(procedure);
//        writer.flush();
//        writer.close();

        //词法分析
        Getsym getsym = new Getsym(procedure);
        getsym.Execute();
        ArrayList<Word> words = getsym.getWords();

//        FileWriter writer = new FileWriter(outfile);
//        for (Word word: words) {
//            writer.write(word.toString() + "\n");
//        }
//        writer.flush();
//        writer.close();

        //语法分析
        Syntax syntax = new Syntax(words);
        CompUnit compunit = (CompUnit) syntax.Execute();

//        FileWriter writer = new FileWriter(outfile);
//        writer.write(compunit.toString());
//        writer.flush();
//        writer.close();

        //错误处理
        ErrorDeal errorDeal = new ErrorDeal(compunit);
        errorDeal.execute();

        FileWriter writer = new FileWriter(outfile);
        FileWriter ewriter = new FileWriter(errorfile);
        if (Table.haveError()) {
            ewriter.write(Table.toError());
            ewriter.flush();
            ewriter.close();
            writer.close();
            System.exit(0);
        }
//        } else {
//            writer.write(compunit.toString());
//        }
        ewriter.close();

        //中间代码
        MediateCode mediateCode = new MediateCode(compunit);
        mediateCode.execute();
        ArrayList<InterRP> interCode = mediateCode.getInterCode();

        for (InterRP interRP: interCode) {
//            System.out.println(interRP.getClass());
//            System.out.println(interRP.toString());
            writer.write(interRP.toString() + "\n");
        }
        writer.flush();
        writer.close();

        //代码生成
        GenerateMips generateMips = new GenerateMips(InterCodeTable.interCode);
        generateMips.generate();
        FileWriter mwriter = new FileWriter(mipsfile);
        mwriter.write(generateMips.toString());
        mwriter.flush();
        mwriter.close();
    }
}
